package com.i360day.invoker;

import com.i360day.invoker.context.HttpInvokerContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

public class DefaultInvokerContext implements ApplicationContextAware, HttpInvokerContext {

    private ApplicationContext parent;

    @Override
    public void setApplicationContext(ApplicationContext parent) throws BeansException {
        this.parent = parent;
    }

    @Override
    public void destroy() throws Exception {
    }

    @Override
    public ApplicationContext getParent() {
        return parent;
    }

    @Override
    public <T> T getBean(String contextName, String beanName, Class<T> type) {
        return getBean(beanName, type);
    }

    @Override
    public <T> T getBean(String beanName, Class<T> type) {
        if (parent.containsBean(beanName)) {
            return (T) parent.getBean(beanName);
        }
        return getBean(type);
    }

    @Override
    public <T> T getBean(Class<T> type) {
        Map<String, T> beansOfType = parent.getBeansOfType(type);
        if (beansOfType.size() == 0) return null;

        return BeanFactoryUtils.beanOfType(parent, type);
    }

    @Override
    public <T> T getBean(Class<T> type, boolean ignoreError) {
        try {
            return getBean(type);
        } catch (Exception ex) {
            // ignore
            if (!ignoreError) {
                throw ex;
            }
        }
        return null;
    }
}
